package reflect;

import reflect.annotations.AutoRunClass;
import reflect.annotations.AutoRunMethod;

import java.io.File;
import java.lang.reflect.Method;

public class Test5 {
    public static void main(String[] args) throws Exception {
        File dir = new File(
                Test4.class.getResource(".").toURI()
        );
        File[] subs = dir.listFiles(f -> f.getName().endsWith(".class"));
        for (File sub : subs) {
            String fileName = sub.getName();
            String className = fileName.substring(0, fileName.lastIndexOf("."));
            String packName = Test4.class.getPackage().getName();
            className = packName + "." + className;
            Class cls = Class.forName(className);
            if (cls.isAnnotationPresent(AutoRunClass.class)) {
                Object obj = cls.newInstance();
                Method[] methods = cls.getDeclaredMethods();
                for (Method method : methods) {
                    if (method.isAnnotationPresent(AutoRunMethod.class)) {
                        AutoRunMethod amr = method.getAnnotation(AutoRunMethod.class);
                        int value = amr.value();
                        System.out.println("开始调用方法：" + method.getName() + "()" + value + "次");
                        for (int i = 0; i < value; i++) {
                            method.invoke(obj);
                        }
                    }
                }
            }
        }
    }
}
